#!/usr/bin/env python
# -*- coding:utf-8 -*-

import asyncore, asynchat, socket, threading, time

HOST = "127.0.0.1"
PORT = 54344

def DEBUG(format, *args) : print format % args

class echo_client(asynchat.async_chat):

    def __init__(self):
        asynchat.async_chat.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connect((HOST, PORT))
        self.set_terminator('\n')
        self.buffer = ""

    def handle_connect(self):
        print "CLIENT Connecting ..."

    def collect_incoming_data(self, data):
        DEBUG('CLIENT collect: >>>%s<<<', data)
        self.buffer = self.buffer + data

    def found_terminator(self):
        print "CLIENT Received:", `self.buffer`
        self.buffer = ""
        self.close()    # ??? while close socket here ???

def main():
    c = echo_client()
    for i in range(10) :
        c.push("hello ")
        c.push("world\n")
    asyncore.loop()

if __name__ == '__main__' :
    main()
    import sys
    sys.exit(0)
